<template>
  <a-spin :spinning="loading">
    <div class="modal-header">
      <div class="modal-title">
        {{ l('Personalized.ColumnColorConfiguration') }}
      </div>
    </div>
    <slot></slot>
    <div class="modal-body">
      <a-form :model="formModel" ref="formRef" style="padding: 8px">
        <a-table
          :columns="columns"
          :data-source="formModel.dataSourceSort"
          bordered
          size="small"
          :rowKey="(record) => record.id"
          :pagination="false"
        >
          <template #bodyCell="{ column, record, index }">
            <a-form-item
              :name="['dataSourceSort', index, column.dataIndex]"
              :rules="[{ required: true, message: '' }]"
              v-if="column.dataIndex === 'colFieldName'"
            >
              <a-select
                v-model:value="record[column.dataIndex]"
                style="width: 100%"
                :options="dataSourceTitleOptions"
                :placeholder="l('PleaseSelect')"
                allowClear
              >
              </a-select>
            </a-form-item>
            <a-form-item
              v-if="column.dataIndex === 'determineType'"
              :name="['dataSourceSort', index, column.dataIndex]"
              :rules="[{ required: true, message: '' }]"
            >
              <a-select
                v-model:value="record[column.dataIndex]"
                style="width: 100%"
                :placeholder="l('PleaseSelect')"
                allowClear
              >
                <a-select-option value="==">{{ '==' }}</a-select-option>
                <a-select-option value="!=">{{ '!=' }}</a-select-option>
                <a-select-option value="<">{{ '<' }}</a-select-option>
                <a-select-option value=">">{{ '>' }}</a-select-option>
                <a-select-option value=">=">{{ '>=' }}</a-select-option>
                <a-select-option value="<=">{{ '<=' }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              v-if="column.dataIndex === 'value'"
              :name="['dataSourceSort', index, column.dataIndex]"
              :rules="[{ required: true, message: '' }]"
            >
              <a-input
                v-model:value="record[column.dataIndex]"
                style="width: 100%"
                :placeholder="l('InputText')"
                allowClear
              />
            </a-form-item>
            <a-form-item
              :name="['dataSourceSort', index, column.dataIndex]"
              v-if="column.dataIndex === 'color'"
            >
              <input type="color" v-model="record[column.dataIndex]" style="height: 32px" />
            </a-form-item>

            <template v-if="column.dataIndex === 'operation'">
              <div class="editable-row-operations" v-if="!record.colFieldName">
                <a @click="del(index, record)">{{ l('Delete') }}</a>
              </div>
              <div class="editable-row-operations" v-else>
                <a-popconfirm
                  :title="l('Personalized.IsConfirmDelete')"
                  :ok-text="l('Yes')"
                  :cancel-text="l('No')"
                  @confirm="del(index, record)"
                >
                  <a>{{ l('Delete') }}</a>
                </a-popconfirm>
              </div>
            </template>
          </template>
        </a-table>
        <a-row justify="center">
          <a-col :span="24">
            <a-button type="dashed" block @click="handleAddClick()">
              <plus-outlined />{{ l('AddLine') }}
            </a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="modal-footer">
      <a-button :disabled="saving" @click="close()" type="button">
        <close-circle-outlined />
        {{ l('Cancel') }}
      </a-button>
      <a-button :disabled="saving" @click="handleResetClick()" type="button">
        {{ l('Reset') }}
      </a-button>
      <a-button :loading="saving" :type="'primary'" @click="handleSave()">
        <save-outlined />
        {{ l('Save') }}
      </a-button>
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { cloneDeep } from 'lodash-es';
  import { defineComponent } from 'vue';
  import {
    ListViewsServiceProxy,
    ListViewColumnColorDto,
    SaveListViewAsPersonalInput,
    ListViewDto,
    ListViewColumnsDto,
    IListViewColumnColorDto,
    IListViewColumnsDto,
  } from '/@/shared/service-proxies';
  import { ModalComponentBase } from '/@/shared/component-base';
  import {
    CheckCircleTwoTone,
    CloseCircleTwoTone,
    PlusOutlined,
    ArrowUpOutlined,
    ArrowDownOutlined,
    AlignLeftOutlined,
    AlignCenterOutlined,
    AlignRightOutlined,
  } from '@ant-design/icons-vue';
  export default defineComponent({
    name: 'ListConfigModal',
    mixins: [ModalComponentBase],
    props: {
      json: {
        type: Object,
        required: true,
        default: {},
      },
    },
    components: {
      CheckCircleTwoTone,
      CloseCircleTwoTone,
      PlusOutlined,
      ArrowUpOutlined,
      ArrowDownOutlined,
      AlignLeftOutlined,
      AlignCenterOutlined,
      AlignRightOutlined,
    },
    data() {
      return {
        listViewsServiceProxy: new ListViewsServiceProxy(this.$apiUrl, this.$api),
        columns: [
          {
            title: this.l('Personalized.Attribute'),
            dataIndex: 'colFieldName',
          },
          {
            title: this.l('Personalized.Operator'),
            dataIndex: 'determineType',
            width: 120,
          },
          {
            title: this.l('TargetValue'),
            dataIndex: 'value',
            width: 120,
            align: 'center',
          },
          {
            title: this.l('Personalized.Color'),
            dataIndex: 'color',
            width: 120,
            align: 'center',
          },
          {
            title: this.l('Action'),
            dataIndex: 'operation',
            width: 200,
          },
        ],
        dataSource: cloneDeep(this.json?.listViewColumns ?? []),
        formModel: {
          dataSourceSort: [] as IListViewColumnColorDto[],
        },
        editableData: {} as any,
      };
    },
    watch: {
      json(val) {
        this.dataSource = cloneDeep(val?.listViewColumns ?? []);
      },
    },
    computed: {
      dataSourceTitleOptions() {
        const arr = this.formModel.dataSourceSort.map((item) => {
          return item.colFieldName;
        });
        return this.dataSource
          .filter((item: ListViewColumnsDto) => {
            // 过滤没有字段
            return !!item.field;
          })
          .sort((a: ListViewColumnsDto, b: ListViewColumnsDto) => {
            //根据sortNum排序
            return (a?.sortNum ?? 0) - (b?.sortNum ?? 0);
          })
          .map((item) => {
            return {
              label: this.l(item.title),
              value: item.field,
              disabled: arr.includes(item.field),
            };
          });
      },
    },
    mounted() {
      this.formModel.dataSourceSort = this.dataSource
        .filter((item: IListViewColumnsDto) => {
          return !!item.listViewColumnColor;
        })
        .map((item: IListViewColumnsDto) => {
          return item.listViewColumnColor;
        });
    },
    methods: {
      /**
       * 重置
       */
      handleResetClick() {
        abp.message.confirm(null, this.l('MessageConfirmOperation'), (isConfirmed: boolean) => {
          if (isConfirmed) {
            this.loading = true;
            this.listViewsServiceProxy
              .deletePersonalListView(this.json.listViewName)
              .then((res) => {
                abp.notify.success(this.l('SavedSuccessfully'));
                this.handleClose();
                this.success();
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },
      handleSave() {
        (this.$refs.formRef as any).validate().then(() => {
          const params = new SaveListViewAsPersonalInput({
            userId: this.abpSession?.userId ?? -1,
            listViewDto: cloneDeep(this.json) as ListViewDto,
          });
          this.formModel.dataSourceSort.map((item: IListViewColumnColorDto) => {
            if (!params.listViewDto.listViewColumns) return;
            const idx = params.listViewDto.listViewColumns.findIndex((i) => {
              return i.field == item.colFieldName;
            });
            if (idx != -1) {
              params.listViewDto.listViewColumns[idx].listViewColumnColor =
                new ListViewColumnColorDto(item);
            }
          });
          this.loading = true;
          this.listViewsServiceProxy
            .saveListViewAsPersonal(params)
            .then(() => {
              this.handleClose();
              this.success(true);
            })
            .finally(() => {
              this.loading = false;
            });
        });
      },
      handleClose() {
        this.editableData = {};
        this.formModel.dataSourceSort = [];
      },

      /****************************** */

      /**
       * 删除
       */
      del(key: number, record) {
        if (!record.id) {
          this.formModel.dataSourceSort.splice(key, 1);
        } else {
          this.loading = true;
          this.listViewsServiceProxy
            .deleteListViewColumnColor(record.id)
            .then(() => {
              abp.notify.success(this.l('SuccessfullyDeleted'));
              this.formModel.dataSourceSort.splice(key, 1);
              this.success(true);
            })
            .finally(() => {
              this.loading = false;
            });
        }
      },
      /**
       * 新增规则
       */
      handleAddClick() {
        this.formModel.dataSourceSort.push({
          id: '',
          colFieldName: undefined,
          determineType: undefined,
          value: undefined,
          color: '#ffffff',
          listViewColumnsId: undefined,
        });
      },
    },
  });
</script>

<style scoped lang="less">
  .ant-form-item {
    margin-bottom: 0;
  }

  :deep(.ant-form-item-with-help .ant-form-item-explain) {
    height: 0;
    min-height: 0;
  }
</style>
